import 'package:bruno/bruno.dart';
import 'package:easy_refresh/easy_refresh.dart';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:sph_driver/Main/MyWallet/BankCardWithdrawal.dart';

import '../../AppConfig/Config.dart';
import '../../AppConfig/RouteAct.dart';
import '../../http/NoLoadingGetApi.dart';
import '../../l10n/messages.dart';
import 'FreightSettlement.dart';


class Withdrawal extends StatefulWidget {

  const Withdrawal({super.key});

  @override
  State<Withdrawal> createState() => _WithdrawalState();
}

class _WithdrawalState extends State<Withdrawal> {
  double distanceToBottom = 0.0;
  String timeTitle="";
  int pageNum=1;
  List dataList=[];
  String timeStart="";
  String timeEnd="";
  @override
  void initState() {
    super.initState();
    getFreightList();
  }
  List chooseTitle=["充值交易","运单交易"];
  List orderNum=["1111111111","222222222","333333333"];


  int isHidden =0;
  int isStarttime=1;
  int listType=0;
  List chooseList=[];
  bool isAll=false;
  String allMoney="0";
  int chooseIndex=1;
  Future _onRefresh() async {
    pageNum=1;
    getFreightList();

  }
  Future onReachBottom()async{
    pageNum=pageNum+1;
    getFreightList();
  }
  void getFreightList(){
    NoLoadinggetApiManager.getData(
      context,
      "api/pay/driver/freight/page",
      {
        "current":pageNum,
        "size":20,
        "category":chooseIndex==1?"UNCLEAR":"CLEARED",
      },
          (responseData)  {
        setState(() {
          if(pageNum==1) {
            dataList = responseData['data']['records'];
          }else{
            if(responseData['data']['records'].isNotEmpty){
              dataList.addAll(responseData['data']['records']);
            }else{
              setState(() {
                pageNum=pageNum-1;
              });

            }
          }
        });

      },
    );
  }

  @override
  int getDaysInMonth(int year, int month) {
    return DateTime(year, month + 1, 0).day;
  }
  @override
  Widget build(BuildContext context) {

    var messages = AppLocalizations.of(context)!;
    final screenSize = MediaQuery.of(context).size;
    return Scaffold(
        backgroundColor: MyColors.backgreyColor,
        appBar: AppBar(
          leading: IconButton(
            icon: Icon(Icons.arrow_back_ios, color: Colors.black),
            onPressed: () => Navigator.of(context).pop(),
          ),
        backgroundColor: Colors.white,
        centerTitle: true,
        title: Text("运费账单",style: TextStyle(color: Colors.black,fontWeight: FontWeight.w300,fontSize: 16.sp),),
        ),
      body: Column(
        children: [
        Expanded(
        child: ListView(
          children: [
            Container(
              margin: EdgeInsets.only(top: 1.h),
              padding: EdgeInsets.only(left: 10.w),
              color: Colors.white,
              child: Column(
                children: [
                  SizedBox(height: 8.h,),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      SizedBox(width: 4.w,),
                      GestureDetector(
                        child:    Column(
                          children: [
                            Text("待结算",style: TextStyle(color:chooseIndex==1?MyColors.themeColor:  Colors.black,fontSize: 16.sp),),
                            Container(
                              width: 10.w,
                              height: 1.h,
                              color: chooseIndex==1?MyColors.themeColor:Colors.white,
                            ),
                          ],
                        ),
                        onTap: (){
                          setState(() {
                            chooseIndex=1;
                            pageNum=1;
                            getFreightList();
                          });

                        },
                      ),
                      SizedBox(width: 4.w,),
                      GestureDetector(
                        child:    Column(
                          children: [
                            Text("已结算",style: TextStyle(color:chooseIndex==2?MyColors.themeColor: Colors.black,fontSize: 16.sp),),
                            Container(
                              width: 10.w,
                              height: 1.h,
                              color: chooseIndex==2?MyColors.themeColor:Colors.white,
                            ),
                          ],
                        ),
                        onTap: (){
                          setState(() {
                            chooseIndex=2;
                            pageNum=1;
                            getFreightList();
                          });
                        },
                      ),
                      SizedBox(width: 4.w,),
                    ],
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      GestureDetector(
                        child: Container(
                          padding: EdgeInsets.only(top: 8.h,bottom: 8.h),
                          child: Row(
                            children: [
                              Text(timeTitle==""?"时间筛选":timeTitle,style: TextStyle(color:Colors.black,fontSize: 14.sp),),
                              Icon(
                                Icons.keyboard_arrow_down,
                                size: 12,color:MyColors.authTipColor,),
                            ],
                          ),
                        ),
                        onTap: ()async{
                          setState(() {
                            if(isHidden==0) {
                              isHidden = 1;
                            }else{
                              isHidden = 0;
                            }
                          });
                          final result= await showModalBottomSheet(
                            context: context,
                            builder: (BuildContext context) {
                              return dataTimeSheet(type: 1,
                              );
                            },
                          );
                          if (result != null) {

                            setState(() {
                              timeTitle=result;
                              if(result.contains("至")){
                                int indexOfZhi = result.indexOf("至");
                                timeStart= result.substring(0, indexOfZhi);
                                timeEnd= result.substring(indexOfZhi + 1);
                                getFreightList();
                              }else{
                                timeStart=result+"01";
                                String endYear=result.substring(0, result.indexOf("-"));
                                String endMonth=result.substring(result.indexOf("-") + 1);
                                timeEnd=result+getDaysInMonth(int.parse(endYear), int.parse(endMonth)).toString();
                                getFreightList();
                              }
                            });
                          }
                        },
                      ),

                    ],
                  ),

                ],
              ) ,

            ),
            EasyRefresh(
              header:
              ClassicHeader(
                dragText: '下拉刷新',
                armedText: '准备释放',
                readyText: '加载中...',
                processingText: '加载中...',
                processedText: '刷新成功',
                noMoreText: '暂无更多',
                failedText: '刷新失败',
                messageText: '刷新时间 %T',
              ),
              footer: ClassicFooter(
                dragText: '加载更多',
                armedText: '准备释放',
                readyText: '加载中...',
                processingText: '加载中...',
                processedText: '加载成功',
                noMoreText: '暂无更多',
                failedText: '加载失败',
                messageText: '加载时间 %T',
              ),
              onRefresh: _onRefresh,
               onLoad:dataList.length>20*pageNum-1?onReachBottom:null,
              child:
                Container(

                  height:chooseIndex==1?screenSize.height-250.h:screenSize.height-90.h,
                  child: ListView.builder(
                      itemCount: dataList.length,
                      itemBuilder: (BuildContext context, int index) {
                        return GestureDetector(
                          child: Container(
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.all(Radius.circular(10)),
                              color: Colors.white,
                            ),
                            margin: EdgeInsets.only(top: 8.h,left: 10.w,right: 10.w),
                            padding: EdgeInsets.only(top:10.h,bottom: 10.h,left:8.w,right: 10.w ),
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Row(
                                  children: [
                                    if(chooseIndex==1)
                                    GestureDetector(
                                        onTap: (){
                                          setState(() {
                                            chooseList.contains(index)?
                                            chooseList.remove(index):chooseList.add(index);
                                            if(chooseList.contains(index)){
                                              allMoney=(double.parse(allMoney)+double.parse(dataList[index]['amount'])).toStringAsFixed(2);

                                            }else{
                                              allMoney=(double.parse(allMoney)-double.parse(dataList[index]['amount'])).toStringAsFixed(2);

                                            }
                                            if(chooseList.length!=dataList.length){
                                              isAll=false;
                                            }
                                          });
                                        },
                                        child: chooseList.contains(index)?Icon(Icons.
                                        check_circle,color: MyColors.themeColor,size: 22)
                                            :Icon(Icons.panorama_fish_eye,color: MyColors.hintColor,size: 22,)),

                                    SizedBox(width: 4.w,),
                                    Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        Row(
                                          children: [
                                            Container(
                                              constraints: BoxConstraints(
                                                maxWidth: screenSize.width-160.w,
                                              ),
                                              child:Text(dataList[index]['productDesc'],style: TextStyle(color: Colors.black,fontSize: 13.sp),overflow: TextOverflow.ellipsis,),
                                            ),


                                          ],
                                        ),
                                        SizedBox(height: 4.w,),
                                        Text("运单号:"+dataList[index]['productId'],style: TextStyle(color: MyColors.textColor,fontSize: 12.sp),),
                                        SizedBox(height: 4.w,),
                                        Text("交易日期:"+dataList[index]['createTime'],style: TextStyle(color: MyColors.textColor,fontSize: 12.sp),),
                                      ],
                                    ),
                                  ],
                                ),

                                Text("¥:"+dataList[index]['amount'],style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp,fontWeight: FontWeight.w600),),
                              ],

                            ),
                          ),
                          onTap: (){
                            if(chooseIndex==1) {
                              setState(() {
                                chooseList.contains(index) ?
                                chooseList.remove(index) : chooseList.add(
                                    index);
                                if (chooseList.contains(index)) {
                                  allMoney = (double.parse(allMoney) +
                                      double.parse(dataList[index]['amount']))
                                      .toStringAsFixed(2);
                                } else {
                                  allMoney = (double.parse(allMoney) -
                                      double.parse(dataList[index]['amount']))
                                      .toStringAsFixed(2);
                                }
                                if (chooseList.length != dataList.length) {
                                  isAll = false;
                                }
                              });
                            }
                          },
                        ) ;

                      }

                  ),
                ),





    ),
              ],
            ),

          ),
          if(chooseIndex==1)
          Container(
            padding: EdgeInsets.all(8.w),
            height: 100.h,
            color: Colors.white,
            child: Column(
              children: [
               Row(
                 mainAxisAlignment: MainAxisAlignment.spaceBetween,
                 children: [
                   Row(
                     children: [
                       GestureDetector(
                           child:Icon(isAll?Icons.check_circle:Icons.panorama_fish_eye,color:isAll?MyColors.themeColor: MyColors.authTipColor,) ,
                        onTap: (){
                        setState(() {
                          isAll=!isAll;
                        if(!isAll){
                          chooseList=[];
                          allMoney="0.00";
                        }else{
                          chooseList=[];
                          chooseList.addAll(List.generate(dataList.length, (index) => index));
                          double sum = 0;
                          for (var index in chooseList) {
                            if (index < dataList.length) {
                              sum += double.parse(dataList[index]['amount']!);
                              allMoney=sum.toStringAsFixed(2);
                            }
                          }
                        }
                        });
                        },
                       ),
                      SizedBox(width: 8.w,),
                       Text("全选",style: TextStyle(color: Colors.black),),
                     ],
                   ),

                   Text("已选择"+(chooseList.length).toString()+"笔交易",style: TextStyle(color: MyColors.textColor)),
                 ],
               ),
                SizedBox(height: 8.h,),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text("提现金额¥"+allMoney,style: TextStyle(color: MyColors.themeColor),),
                        Text("单笔提现限额"+"10000"+"元",style: TextStyle(color: MyColors.hintColor),),
                      ],
                    ),
                    GestureDetector(
                      child:    Container(
                          width: 160.w,
                          height: 30.h,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.all(Radius.circular(30)),
                            color: MyColors.themeColor,
                          ),

                          child: Center(
                            child: Text("去结算",style: TextStyle(color: Colors.white,fontSize: 14.sp,fontWeight: FontWeight.w600),),
                          )
                      ),
                      onTap: ()async{
                        if(chooseList.isEmpty){

                        }else{

                          List billIdList=[];
                          for (var index in chooseList) {
                            if (index < chooseList.length) {
                              billIdList.add(dataList[index]['id']);
                              print(billIdList);
                            }
                          }
                       final result=await   Navigator.push( context, FadeRoute(page:FreightSettlement(billMap: {"billIdList":billIdList,"allMoney":allMoney},)));
                        if(result!=null){
                          getFreightList();
                          setState(() {
                            chooseList=[];
                          });

                        }
                        }

                      },
                    ),


                  ],
                )
              ],
            ),
          ),
        ],
      ),
    );

  }
}
class dataTimeSheet extends StatefulWidget {
  const dataTimeSheet({super.key, required this.type});
  final int type;
  @override
  State<dataTimeSheet> createState() => _dataTimeSheetState();
}

class _dataTimeSheetState extends State<dataTimeSheet> {
  DateTime selectedDate = DateTime.now();
  int selectedYear = DateTime.now().year;
  int selectedMonth = DateTime.now().month;
  int selectedDay = DateTime.now().day;
  int selectedHour = DateTime.now().hour;
  late List<int> years;
  late FixedExtentScrollController yearController;
  late FixedExtentScrollController monthController;
  late FixedExtentScrollController dayController;
  late FixedExtentScrollController hourController;
  String startTime ="${DateTime.now().year}-${DateTime.now().month}-${DateTime.now().day}";
  String endTime ="";
  int timeType=1;
  @override
  void initState() {
    super.initState();

    DateTime selectedDate = DateTime.now();
    int selectedYear = DateTime.now().year;
    int selectedMonth = DateTime.now().month;
    int selectedDay = DateTime.now().day;
    int selectedHour = DateTime.now().hour;
    int currentYear = DateTime.now().year;
    years = List.generate(6, (index) => currentYear + index);
    // 设置初始滚动位置
    yearController = FixedExtentScrollController(initialItem: years.indexOf(selectedYear));
    monthController = FixedExtentScrollController(initialItem: selectedMonth - 1);
    dayController = FixedExtentScrollController(initialItem: selectedDay - 1);
    hourController = FixedExtentScrollController(initialItem: selectedHour);
  }
  @override
  int getDaysInMonth(int year, int month) {
    return DateTime(year, month + 1, 0).day;
  }

  Widget build(BuildContext context) {
    return Container(
        padding: EdgeInsets.only(left: 10.w,right: 10.w,top: 10.w,bottom: 40.h),
        height: 330.h,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(10)),
          color: Colors.white,
        ),
        child:Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                TextButton(onPressed: (){
                  Navigator.pop(context);
                }, child: Text("取消",style: TextStyle(color: Colors.black,fontSize: 14.sp),)),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(Icons.access_time,color: MyColors.textColor,),
                    Text("选择时间",style:TextStyle(color: Colors.black,fontSize: 16.sp),),
                  ],
                ),

                TextButton(onPressed: (){
                  if(startTime==""){
                    BrnToast.show("请选择开始时间", context);
                  }else if(endTime==""){
                    BrnToast.show("请选择结束时间", context);
                  }else{

                    Navigator.pop(context,startTime+"至"+endTime);
                  }

                }, child: Text("确定",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp))),
              ],
            ),
            Divider(height: 16.h,color: MyColors.backgreyColor,),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                SizedBox(width: 10.w,),
                GestureDetector(
                  child:  Column(
                    children: [
                      Text(startTime==""?"开始时间":startTime,style: TextStyle(color:timeType==1?MyColors.themeColor: Colors.black,fontSize: 13.sp),),
                      Container(
                        height: 2.h,width:20.w,
                        color:timeType==1? MyColors.themeColor:Colors.white,
                      )
                    ],
                  ),
                  onTap: (){
                    setState(() {
                      timeType=1;
                    });
                  },
                ),

                Text("至",style: TextStyle(color: MyColors.textColor,fontSize: 13.sp),),
                GestureDetector(
                  child: Column(
                    children: [
                      Text(endTime==""?"结束时间":endTime,style: TextStyle(color: timeType==2?MyColors.themeColor: Colors.black,fontSize: 13.sp),),
                      Container(
                        height: 2.h,width:20.w,
                        color:timeType==2? MyColors.themeColor:Colors.white,
                      )
                    ],
                  ),
                  onTap: (){
                    setState(() {
                      timeType=2;
                    });
                  },
                ),

                SizedBox(width: 10.w,),
              ],
            ),
            Divider(height: 16.h,color: MyColors.backgreyColor,),

            Text("时间格式:年-月-日",style: TextStyle(color: Colors.black),),
            SizedBox(height: 4.h,),
            Container(
              decoration: BoxDecoration(
                border: Border.all(
                  color: Color.fromRGBO(224, 227, 234, 1),
                  width: 1,
                ),
                borderRadius: BorderRadius.circular(5.0), // 可选，添加圆角
              ),
              child:  Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  _buildPicker(
                    items: generateYearList(),
                    controller: yearController,
                    onChanged: (value) {
                      setState(() {
                        selectedYear = value;
                        timeType==1?startTime=selectedYear.toString()+"-"+selectedMonth.toString().padLeft(2, '0')+"-"+selectedDay.toString().padLeft(2, '0')+" "
                            :endTime=selectedYear.toString()+"-"+selectedMonth.toString().padLeft(2, '0')+"-"+selectedDay.toString().padLeft(2, '0');
                      });
                    },
                  ),
                  _buildPicker(
                    items: List.generate(12, (index) => index + 1),
                    controller: monthController,
                    onChanged: (value) {
                      setState(() {
                        selectedMonth = value;
                        timeType==1?startTime=selectedYear.toString()+"-"+selectedMonth.toString().padLeft(2, '0')+"-"+selectedDay.toString().padLeft(2, '0')+" "
                            :endTime=selectedYear.toString()+"-"+selectedMonth.toString().padLeft(2, '0')+"-"+selectedDay.toString().padLeft(2, '0');
                      });
                    },
                  ),
                  _buildPicker(
                    items: List.generate(getDaysInMonth(selectedYear, selectedMonth), (index) => index + 1),
                    controller: dayController,
                    onChanged: (value) {
                      setState(() {
                        selectedDay = value;
                        timeType==1?startTime=selectedYear.toString()+"-"+selectedMonth.toString().padLeft(2, '0')+"-"+selectedDay.toString().padLeft(2, '0')+" "
                            :endTime=selectedYear.toString()+"-"+selectedMonth.toString().padLeft(2, '0')+"-"+selectedDay.toString().padLeft(2, '0');
                      });
                    },
                  ),
                  // _buildPicker(
                  //   items: List.generate(24, (index) => index),
                  //   controller: hourController,
                  //   onChanged: (value) {
                  //     setState(() {
                  //       selectedHour = value;
                  //       timeType==1?startTime=selectedYear.toString()+"-"+selectedMonth.toString().padLeft(2, '0')+"-"+selectedDay.toString().padLeft(2, '0')+" "
                  //           :endTime=selectedYear.toString()+"-"+selectedMonth.toString().padLeft(2, '0')+"-"+selectedDay.toString().padLeft(2, '0');
                  //     });
                  //   },
                  // ),
                ],
              ),
            ),


          ],
        )



    );
  }
  Widget _buildPicker({
    required List<int> items,
    required FixedExtentScrollController controller,
    required ValueChanged<int> onChanged,
  }) {
    return Container(
      height: 150.0,
      width: 80.0,
      child: CupertinoPicker(
        itemExtent: 40.0,
        onSelectedItemChanged: (index) {
          onChanged(items[index]);
        },
        selectionOverlay: _buildSelectionOverlay(),
        children: items.map((item) => _buildPickerItem(item)).toList(),
        // 使用初始化的控制器
        scrollController: controller,
      ),
    );
  }

  Widget _buildPickerItem(int item) {
    // 将月份和日期格式化为两位数
    String formattedItem = item.toString().padLeft(2, '0');

    return Container(
      alignment: Alignment.center,
      child: Text(formattedItem),
    );
  }

  Widget _buildSelectionOverlay() {
    return Container(
      height: 40.0,
      decoration: BoxDecoration(
        border: Border(
          top: BorderSide(color: Color.fromRGBO(220, 224, 231, 1), width: 1.0.h),
          bottom: BorderSide(color: Color.fromRGBO(220, 224, 231, 1), width: 1.0.h),
        ),
      ),
    );
  }

  // 生成年份列表，包括当前年份和之后的5年
  List<int> generateYearList() {
    int currentYear = DateTime.now().year;
    List<int> years = List.generate(6, (index) => currentYear + index);
    return years;
  }
}